﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BenzInfo.Hockey.Grenadiers.Models;
using BenzInfo.Hockey.Grenadiers.Utils;

namespace BenzInfo.Hockey.Grenadiers.Controllers
{ 
    public class PlayersController : BaseController
    {
        private GrenadiersContext db = new GrenadiersContext();

        private const string BASE_PATH = "~/Content/images/players";

        //
        // GET: /Player/

        public ViewResult Index(int teamId = 0)
        {
            List<Team> teams = db.Teams.Where(t => t.Name == "Grenadiers").OrderByDescending(t => t.Year).ToList();

            ViewBag.Teams = (from t in teams
                            select new SelectListItem
                            {
                                Value = t.Id.ToString(),
                                Text = string.Format("{0} {1}-{2}", t.Name, t.Year-1, t.Year),
                                Selected = t.Id == teamId
                            }).ToList();

            Team team = teamId > 0 ? db.Teams.Find(teamId) : teams.First();

            return team.Year > 2012 ? View(team) : View("Archive", team);
        }

        //
        // GET: /Player/Create

        public ActionResult Create()
        {
            return PartialView();
        } 

        //
        // POST: /Player/Create

        [HttpPost]
        public ActionResult Create(Player player, HttpPostedFileBase inputFile, int teamId)
        {
            if (inputFile != null)
            {
                using (Image img = Image.FromStream(inputFile.InputStream))
                {
                    string ext = inputFile.FileName.Split('.')[inputFile.FileName.Split('.').Length - 1];
                    string filename = string.Format("{1}_{0:000}.{2}", DateTime.Now.Ticks, player.Id, ext);
                    string filepath = string.Format("{0}/{1}", Server.MapPath(BASE_PATH), filename);

                    ImageHelper.Save(img, filepath, ext);

                    player.Picture = filename;
                }
            }

            if (ModelState.IsValid)
            {
                player.Position = db.Players.Count() + 1;

                Team team = db.Teams.Find(teamId);
                
                team.Players.Add(player);

                //db.Entry(player).State = EntityState.Modified;
                //db.Entry(team).State = EntityState.Modified;

                db.SaveChanges();
                return RedirectToAction("Index", new { teamId = team.Id });  
            }

            return PartialView(player);
        }

        //
        // GET: /Player/EditPosition

        public void EditPosition(int[] items)
        {
            int i = 1;
            foreach (int id in items)
            {
                Player p = db.Players.Find(id);
                p.Position = i++;
                db.Entry(p).State = EntityState.Modified;
            }

            db.SaveChanges();
        }
        
        //
        // GET: /Player/Edit/5

        public ActionResult Edit(int id, int teamId)
        {
            Player player = db.Players.Find(id);
            return PartialView(player);
        }
        
        //
        // POST: /Player/Edit/5

        [HttpPost]
        public ActionResult Edit(Player player, HttpPostedFileBase inputFile, string nopicture, int teamId)
        {
            if (inputFile != null)
            {
                using (Image img = Image.FromStream(inputFile.InputStream))
                {
                    string ext = inputFile.FileName.Split('.')[inputFile.FileName.Split('.').Length - 1];
                    string filename = string.Format("{1}_{0:000}.{2}", DateTime.Now.Ticks, player.Id, ext);
                    string filepath = string.Format("{0}/{1}", Server.MapPath(BASE_PATH), filename);

                    ImageHelper.Save(img, filepath, ext);

                    player.Picture = filename;
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(player).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", new { teamId = teamId });
            }

            return PartialView(player);
        }

        //
        // GET: /Player/Delete/5
 
        public ActionResult Delete(int id, int teamId)
        {
            Player player = db.Players.Find(id);
            return PartialView(player);
        }

        //
        // POST: /Player/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id, int teamId)
        {            
            Player player = db.Players.Find(id);
            db.Players.Remove(player);
            db.SaveChanges();
            return RedirectToAction("Index", new { teamId = teamId });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}